package com.blockchain.service.impl;

import com.blockchain.model.User;
import com.blockchain.repository.UserRepository;
import com.blockchain.service.UserService;
import com.blockchain.service.dto.LoginRequestDTO;
import com.blockchain.service.dto.RegistrationRequestDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;
    @Autowired
    public UserServiceImpl(UserRepository userRepository){
        this.userRepository=userRepository;
    }
    @Override
    public void registerUser(RegistrationRequestDTO registrationRequestDTO) {
        //实现注册逻辑
        User user=new User();
        user.setUsername(registrationRequestDTO.getUsername());
        user.setPassword(registrationRequestDTO.getPassword());
        user.setEmail(registrationRequestDTO.getEmail());

        //保存到数据库
        userRepository.save(user);
    }
    @Override
    public void loginWithUsernameAndPasswordUser(LoginRequestDTO loginRequestDTO)
    {
        //实现登录逻辑
        String username=loginRequestDTO.getUsername();
        String password=loginRequestDTO.getPassword();

        //根据用户名查找数据库
        User user= userRepository.findByUsername(username);


        //检查用户是否存在
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        if(!user.getPassword().equals(password)){
            throw new BadCredentialsException("密码错误");
        }

    }


    @Override
    public void loginWithEmailUser(LoginRequestDTO loginRequestDTO){

        String email=loginRequestDTO.getEmail();
        User user=userRepository.findByEmail(email);

        if(user!=null){

        }

    }
    @Override
    public boolean checkUsernameDuplicateUser(RegistrationRequestDTO registrationRequestDTO){
        //检查是否存在重复用户
        String username=registrationRequestDTO.getUsername();


        //用户名检查
        User userByUsername=userRepository.findByUsername(username);
        if(userByUsername!=null){
            return true;
        }
        return false;
    }
    @Override
    public boolean checkEmailDuplicateUser(RegistrationRequestDTO registrationRequestDTO){

        String email=registrationRequestDTO.getEmail();

        //手机号检查
        User userByEmail=userRepository.findByEmail(email);
        if(userByEmail!=null){
            return true;
        }
        return false;
    }

    @Override
    public void deleteUser(Long userId){
        userRepository.deleteById(userId);
    }
}
